package com.company.app.test;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageViewerJFrame extends JFrame {
  private JPanel containPanel;
  private JPanel imgPanel;
  private JPanel btnPanel;
  private JButton btnRotate;
  private BufferedImage img;
  private int rotationCount = 0;

  public ImageViewerJFrame() {
    String filePath = "C:\\Users\\user\\Documents\\000-111\\000.png";
    // 初始化组件
    containPanel = new JPanel(new BorderLayout());
    imgPanel = new JPanel() {
      @Override
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (img != null) {
          Graphics2D g2d = (Graphics2D) g;
          // 创建一个新的AffineTransform对象
          AffineTransform transform = new AffineTransform();
          // 将原点平移到图片的中心点
          transform.translate(img.getWidth() / 2.0, img.getHeight() / 2.0);
          // 根据旋转次数计算旋转角度，并应用旋转变换
          transform.rotate(Math.toRadians(rotationCount * 45));
          // 将原点平移回原来的位置
          transform.translate(-img.getWidth() / 2.0, -img.getHeight() / 2.0);
          // 应用变换到Graphics2D对象
          g2d.setTransform(transform);
          // 绘制图片
          g2d.drawImage(img, transform, null);
        }
      }
    };
    btnPanel = new JPanel();
    btnRotate = new JButton("Rotate");

    // 加载图片
    try {
      img = ImageIO.read(new File(filePath));
    } catch (IOException e) {
      e.printStackTrace();
    }

    // 设置布局管理器
    containPanel.setLayout(new BorderLayout());
    btnPanel.setLayout(new FlowLayout());

    // 添加组件到JPanel
    containPanel.add(imgPanel, BorderLayout.CENTER);
    btnPanel.add(btnRotate);

    // 将JPanel添加到JFrame
    this.add(containPanel);
    this.add(btnPanel, BorderLayout.SOUTH);

    // 设置JFrame属性
    this.setTitle("Image Viewer JFrame");
    this.setSize(400, 400);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);

    // 添加按钮点击事件监听器
    btnRotate.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        rotationCount++;
        imgPanel.repaint();
      }
    });
  }

  public void test() {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        new ImageViewerJFrame().setVisible(true);
      }
    });
  }
}